package com.example.demo.common.com.example.demo;

import java.util.HashMap;

public class xymodule {

    public static void main(String[] args) {
        WebSiteFactory webSiteFactory = new WebSiteFactory();
        User sina = new User("新浪");
        User huawei = new User("华为");
        User amazon = new User("亚马逊");
        WebSite portal = webSiteFactory.getWebSiteCategory("门户类");
        WebSite enterprise = webSiteFactory.getWebSiteCategory("企业类");
        WebSite sale = webSiteFactory.getWebSiteCategory("销售类");
        portal.use(sina);
        enterprise.use(huawei);
        sale.use(amazon);
        System.out.println("网站类型总数：" + webSiteFactory.getWebSiteCount());
    }

    static class WebSiteFactory {//享元工厂类
        private HashMap<String, ConcreteWebSite> pool = new HashMap<>();//充当池的作用

        //根据网站的类型，在池中返回一个网站
        public WebSite getWebSiteCategory(String type) {
            if (!pool.containsKey(type)) {
                //若池中没有该类型的网站，在池中创建一个网站，并返回
                pool.put(type, new ConcreteWebSite(type));
            }
            return pool.get(type);
        }

        //获取池中有多少个网站类型
        public int getWebSiteCount() {
            return pool.size();
        }
    }


    static abstract class WebSite {//抽象享元角色

        public abstract void use(User user);
    }

    static class ConcreteWebSite extends WebSite {//具体的享元角色
        private String type;//内部状态

        public ConcreteWebSite(String type) {
            this.type = type;
        }

        @Override
        public void use(User user) {
            System.out.println("网站形式：" + type + "，用户：" + user.name);
        }

    }

    static class User {//不可共享角色
        public String name;//外部状态

        public User(String name) {
            this.name = name;
        }
    }
}
